package com.mtw.bbs.reply.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mtw.bbs.article.feign.ArticleClient;
import com.mtw.bbs.article.pojo.vo.SimpleArticleVo;
import com.mtw.bbs.common.core.security.UserDetails;
import com.mtw.bbs.common.core.security.context.SecurityContextHolder;
import com.mtw.bbs.common.core.util.BeanCopyUtils;
import com.mtw.bbs.constant.ReplyConstant;
import com.mtw.bbs.constant.ReplyLevelEnum;
import com.mtw.bbs.reply.pojo.dto.ReplyDto;
import com.mtw.bbs.reply.pojo.entity.ReplyIndex;
import com.mtw.bbs.reply.pojo.vo.ReplyVo;
import com.mtw.bbs.reply.service.ReplyIndexService;
import com.mtw.bbs.common.core.constant.BusinessObjectType;
import com.mtw.bbs.common.core.constant.SysConstant;
import com.mtw.bbs.common.core.enums.SortEnum;
import com.mtw.bbs.common.core.vo.Result;
import com.mtw.bbs.userAdmin.feign.UserClient;
import com.mtw.bbs.userAdmin.pojo.dto.UserDto;
import com.mtw.bbs.userAdmin.pojo.vo.UserInfoVo;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * 用户评论
 */
@RestController
@RequestMapping("open/reply")
@RequiredArgsConstructor
public class OpenReplyController {

    private final UserClient userClient;
    private final ArticleClient articleClient;
    private final ReplyIndexService replyIndexService;


    /**
     * 分页获取文章的评论
     *
     * @param page      当前页
     * @param size      分页大小
     * @param articleId 文章id
     * @param sort      排序方式
     */
    @GetMapping("/getRelyList/article/{articleId}")
    public Result getRelyList(@PathVariable(name = "articleId") String articleId,
                              @RequestParam(name = "page") int page,
                              @RequestParam(name = "size") int size,
                              @RequestParam(name = "sort", required = false) Integer sort) {


        QueryWrapper<ReplyIndex> qw = new QueryWrapper<>();
        qw.eq("r.status", SysConstant.DEFAULT_ENABLE);
        qw.eq("r.root_id", ReplyConstant.DEFAULT_ROOT_ID);
        qw.eq("r.parent_id", ReplyConstant.DEFAULT_ROOT_ID);
        qw.eq("r.object_type", BusinessObjectType.ARTICLE);
        qw.eq("r.object_id", articleId);

        if (SortEnum.SORT_TIME.getCode().equals(sort)) {
            qw.orderByDesc("r.created_date");
        } else {
            qw.orderByDesc("ri.like_count");
        }

        if (sort == null) {
            sort = SortEnum.SORT_LIKE.getCode();
        }
        Page<ReplyVo> voPage = replyIndexService.getReplyVoPageWithSon(qw, sort, page, size,  ReplyLevelEnum.REPLY_LEVEL_ONE, 2);
        return Result.success(voPage);
    }


    /**
     * 分页获取文章的子评论
     *
     * @param page     当前页
     * @param size     分页大小
     * @param parentId 父id
     * @param sort     排序方式
     */
    @GetMapping("/getSonList/article/{parentId}")
    public Result getSonRlyList(@PathVariable(name = "parentId") String parentId,
                                @RequestParam(name = "page") int page,
                                @RequestParam(name = "size") int size,
                                @RequestParam(name = "sort", required = false) Integer sort) {


        QueryWrapper<ReplyIndex> qw = new QueryWrapper<>();
        qw.eq("r.status", SysConstant.DEFAULT_ENABLE);
        qw.eq("r.root_id", parentId);
        qw.eq("r.parent_id", parentId);

        if (SortEnum.SORT_TIME.getCode().equals(sort)) {
            qw.orderByDesc("r.created_date");
        } else {
            qw.orderByDesc("ri.like_count");
        }

        if (sort == null) {
            sort = SortEnum.SORT_LIKE.getCode();
        }
        Page<ReplyVo> voPage = replyIndexService.getReplyVoPageWithSon(qw, sort, page, size, ReplyLevelEnum.REPLY_LEVEL_TWO, 4);
        return Result.success(voPage);
    }


    /**
     * 分页获取文章的子评论的子评论
     *
     * @param page     当前页
     * @param size     分页大小
     * @param parentId 父id
     * @param sort     排序方式
     */
    @GetMapping("/getLowerLevelList/article/{parentId}")
    public Result getLowerLevelRlyList(@RequestParam(name = "page") int page,
                                       @RequestParam(name = "size") int size,
                                       @PathVariable(name = "parentId") String parentId,
                                       @RequestParam(name = "sort", required = false) Integer sort) {


        QueryWrapper<ReplyIndex> qw = new QueryWrapper<>();
        qw.eq("r.status", SysConstant.DEFAULT_ENABLE);
        qw.eq("r.dialog", parentId);

        if (SortEnum.SORT_TIME.getCode().equals(sort)) {
            qw.orderByDesc("r.created_date");
        } else {
            qw.orderByDesc("ri.like_count");
        }

        if (sort == null) {
            sort = SortEnum.SORT_LIKE.getCode();
        }
        Page<ReplyVo> voPage = replyIndexService.getReplyVoPageWithSon(qw, sort, page, size, ReplyLevelEnum.REPLY_LEVEL_THREE, 4);
        return Result.success(voPage);
    }


    /**
     * 分页获取指定用户发布的评论
     *
     * @param username 用户名
     * @param page     当前页
     * @param size     分页大小
     * @param sort     排序方式
     */
    @GetMapping("/userArticle/{username}")
    public Result getArticleReplyByUser(@PathVariable("username") String username,
                                        @RequestParam(name = "page") int page,
                                        @RequestParam(name = "size") int size,
                                        @RequestParam(name = "sort", required = false) Integer sort) {

        Result<UserDto> userinfo = userClient.getUserInfoByUsername(username);
        if (userinfo.isFail() || userinfo.getData() == null) {
            return Result.fail("用户不存在或已禁用");
        }

        QueryWrapper<ReplyIndex> qw = new QueryWrapper<>();
        qw.eq("r.created_by", userinfo.getData().getId());
        qw.eq("r.status", SysConstant.DEFAULT_ENABLE);
        qw.eq("r.object_type", BusinessObjectType.ARTICLE);
        if (SortEnum.SORT_LIKE.getCode().equals(sort)) {
            qw.orderByDesc("ri.like_count");
        } else {
            qw.orderByDesc("r.created_date");
        }
        UserInfoVo infoVO = userinfo.getData().toSimpleInfoVO();
        UserDetails user = SecurityContextHolder.getContext().getAuthentication();

        Page<ReplyDto> dtoPage = replyIndexService.getUserReplyVoPage(page, size, user == null ? null : user.getId(), qw);

        Page<ReplyVo> voPage = new Page<>(page,size,dtoPage.getTotal());
        if (!dtoPage.getRecords().isEmpty()){

            // 查文章
            Map<String, SimpleArticleVo> articleMap = new HashMap<>(0);
            Result<List<SimpleArticleVo>> articleResult = articleClient.getArticleById(dtoPage.getRecords().stream().map(ReplyDto::getObjectId).toArray(String[]::new));
            if (articleResult.isSuccess()){
                articleMap =  articleResult.getData().stream().collect(Collectors.toMap(SimpleArticleVo::getId, Function.identity()));
            }

            Map<String, SimpleArticleVo> finalArticleMap = articleMap;
            List<ReplyVo> voList = dtoPage.getRecords().stream().map(x -> {
                ReplyVo vo = BeanCopyUtils.copyBean(x, ReplyVo.class);
                vo.setObjectInfo(finalArticleMap.get(x.getObjectId()));
                vo.setPoster(infoVO);
                return vo;
            }).toList();
            voPage.setRecords(voList);

        }

        return Result.success(voPage);
    }


}
